<template>
  <div class="sell">
    <div class="header">
      <div style="font-size: 20px;">
        销售总额: {{totalMoney}} 元
        销售总数：{{totalNum}}
        </div>
      <div class="form">
        <el-form>
          <el-form-item>
            <el-input v-model="keywords" placeholder="请输入商品编号或者名称" clearable>
              <el-button slot="append" icon="el-icon-search" @click="getProductsByKeyWords"/>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="table">
      <el-table :data="list" border fit>
        <el-table-column label="编号" align="center">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="商品价格" align="center">
          <template slot-scope="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>

        <el-table-column label="库存（件）" align="center">
          <template slot-scope="scope">
            {{ scope.row.inventory }}
          </template>
        </el-table-column>

        <el-table-column label="销量（件）" align="center">
          <template slot-scope="scope">
            {{ scope.row.sale_count }}
          </template>
        </el-table-column>

        <el-table-column label="销量额（元）" align="center">
          <template slot-scope="scope">
            {{scope.row.sale_money}}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
    :total="total"
    :page.sync="listQuery.page"
    :limit.sync="listQuery.limit"
    @pagination="getList" />

    <div id="main" :style="{width: '100%', height: '300px'}"></div>
  </div>
</template>
<script>
import productApi from '@/api/product.js'
import categoryDetailApi from '@/api/categoryDetail.js'
import Pagination from '@/components/Pagination'
const echarts = require('echarts');
export default {
  components: {
    Pagination
  },
  data() {
    return {
      keywords: '', // 搜索关键字
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },
      totalMoney: 0,
      totalNum: 0,
      loading: false, // loading状态
      categoryDetail: [],
      option: {
        title: {
            text: '商品类别销售量'
          },
          tooltip: {},
          xAxis: {
              data: []
          },
          yAxis: {},
          series: [{
              name: '销量',
              type: 'bar',
              data: []
          }]
      }
  }
},
  created() {
    this.getCategoryDetails()
    this.getList()
    this.getTotalMoney()
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById('main'))
      // 绘制图表
      myChart.setOption(this.option)
    },
    // 获取商品明细
    async getCategoryDetails() {
      const query = {
        page: this.listQuery.page -1,
        limit: 99999999
      }
      const result = await categoryDetailApi.getCategoryDetails(query)
      let list = result.data.rows
      let data = []
      list.forEach(value => {
        data.push(value.name)
      })
      this.option.xAxis.data = data
      this.categoryDetail = list
      this.init()
      console.log(this.option)
    },
    // 获取全部商品
    async getList(e) {
      const query = {}
      if(e == undefined) {
        query.page = this.listQuery.page - 1,
        query.limit = this.listQuery.limit
      }
      else {
        query.page = e.page - 1,
        query.limit = e.limit
      }
      const result = await productApi.getProducts(query)
      this.list = result.data.rows
      this.total = result.data.count
      this.list.forEach(value => {
        if(value.sale_count === null) {
          value.sale_count = 0
        }
        value.sale_money = parseInt(value.sale_count)*parseInt(value.price)
      })
    },
    // 获取总销售额,总销售量
    async getTotalMoney() {
      const query = {
        page: this.listQuery.page -1,
        limit: 99999999
      }
      const result = await productApi.getProducts(query)
      const list = result.data.rows
      let sum = 0
      let count = 0
      list.forEach(value => {
        if(value.sale_count === null) {
          value.sale_count = 0
        }
        value.sale_money = parseInt(value.sale_count)*parseInt(value.price)
        sum+=value.sale_money
        value.total_count = parseInt(value.sale_count)
        count+=value.total_count
      })
      let sale_count = 0
      let data = []
      this.categoryDetail.forEach(value => {
        this.getSaleByCategory(value.id)
      })
      console.log(this.option)
      this.totalMoney = sum
      this.totalNum = count
      this.init()
    },
    // 
    async getSaleByCategory(id) {
      const result = await productApi.getSaleByCategory(id)
      let list = []
      let count = 0
      if(result.data.length > 0) {
        result.data.forEach(value => {
          if(value.sale_count) {
            list.push(value.sale_count)
          }
        })
      }else {
        result.data.forEach(value => {
          list.push(0)
        })
      }
      let sale = eval(list.join("+"))
      this.option.series[0].data.push(sale)
      this.init()
    },
    // 根据搜索关键字获取商品
    async getProductsByKeyWords() {
      if(this.keywords) {              //搜索关键字不为空
        const query = {}
        if(Number(this.keywords)) {
          query.id = this.keywords
        }else {
          query.name = this.keywords
        }
        const result = await productApi.getProductsByKeyWords(query)
        if(result.code == 0) {
          this.list = []
          this.list = result.data
          result.data.forEach(value => {
            if(value.hot ===0) {
              value.hot = false
            }else {
              value.hot = true
            }
          })
        }
      }else {                        // 搜索关键字为空
        this.getList()
      }
    }
  },
  inject: ['reload']
}
</script>
<style lang="less" scoped>
  .sell {
    margin: 30px;
    position: relative;
    .header {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
  }
</style>
